$(document).ready(function() {
	var logger = $("#log");
	
	/**
	$("#user_btn_container").css({
	  	top: $(window).height() - 50,
	  	left: $(window).width() - 400
	});
	*/
	
	/**
	 * Data structure to store the user chat history
	 * @Format 
	 * {
	 * 	email1 : {
	 * 		name: 'Test',
	 * 		history: 'Chat...History..'		
	 * 	},
	 *  email2 : {
	 *  	name: 'Test Another',
	 *  	history: 'Another... Oh~ ho'
	 *  }
	 * }
	 */
	var data;
	var appendData = function(name, email){
		var oneThread;
		oneThread['name'] = name;
		oneThread['history'] = '';
		data.email = oneThread;
	}
	
	var updateData = function(email, newHistory){
		thread = data.email;
		thread['history'] = newHistory;
		data.email = thread;
	}
	
	var updateUserList = function(){
		$.ajax({
			type: 'GET',
			url: '/inituser?time=' + Math.random(),
			data: '',
			success: function(data){
				var jsonData = eval("(" + data + ")");
				var userHTML = '';
				$.each(jsonData,function(idx, item){
					userHTML += '<p> <a href="#" email="' + item.email + '" class="single_user" name="' + item.name + '">' + item.name + '</a></p>';
					//TODO If there are multiple friends chat online...
					//appendData(item.name, item.email);
				});
				$("#all_list_users").html(userHTML);
				rigisterOpenEvent();
			}
		});
		setTimeout(updateUserList, 5000);
	}
	
	var initSession = function(){
		var userName = $("#name").val();
		var param = "username=" + userName + "&email=" + $("#loginemail").val();
		$.ajax({
			type: "GET",
			url: '/login',
			data: param,
			success: function(data){
				$("#login_form").dialog("close");
				updateUserList();
			}
		});
	}
	
	function checkRegexp( o, regexp, n ) {
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass( "ui-state-error" );
			setTimeout(function(){
				o.removeClass("ui-state-error", 1500);
			}, 2000);
			return false;
		} else {
			return true;
		}
	}
	
	var checkInSession = function(){
		if(isInSession && typeof(isInited) == 'undefined'){
			$("#login_form").dialog({
				height: 235,
				width: 350,
				modal: true,
				closeOnEscape: false,
				buttons: {
					"Goto Chat Now >>" : function(){
						isValid = checkRegexp( $("#loginemail"), /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
						if(isValid){
							initSession();
						}
					}
				}
			});
		}
	}
	checkInSession();
	
	
	
	/**
	 * Hide user lists
	 */
	$("#all_list_users").hide();
	$("#chat_dialog").hide();
	
    /**
     * Create User list Button
     */
    $("#user_list_btn").button({
    	icons: {
            secondary: "ui-icon-triangle-1-s"
    	}
    });
    
    /**
     * Adding click action on the button
     */
    $("#user_list_btn").click(function(){
    	$("#all_list_users").toggle();
    });
    $("#user_list_btn").css({
    	width: 163
    })
    
    /**
     * Add click event on listed users
     */
    var rigisterOpenEvent = function(){
    	$(".single_user").click(function(){
        	$("#chat_dialog").dialog({
            	position: ['right', 'bottom'],
            	resizable: false,
            	draggable: false,
            	height: 300,
            	width: 300,
            	title: $(this).attr('name')
            });
        	$("#to").attr('value', $(this).attr('email'));
        	
        	//Close the opened user list
        	$("#all_list_users").toggle();
        });
    }
    rigisterOpenEvent();
    
    /**
     * Creating the sending msg button
     */
    $("#submit_input").button({
    	label : 'Submit Message'
    });
    $("#submit_input").click(function(){
    	//alert("Message start to send...");
    	//Handle the Ajax request and response
    	/**
    	$.get(
    		"/message",
    		{
    			name: "John",
    			content: "Hello"
    		}
    		function(msg){
    			alert("Data saved: " + msg);
    		}
    	);
    	*/
    	sendMessageToServer();
    });
    
    /**
     * Send message to server side.
     */
    var sendMessageToServer = function(){
    	var msg = $("#chat_input").val();
    	var param = "msg=" + msg + "&to=" + $("#to").val(); 
    	param = encodeURI(param);
    	$.ajax({
	    	type: "GET",
	    	url: "/message",
	    	data: param,
	    	success: function(msg){
	    		//...
			}
	    });
    	//Reset value of input textarea
    	$("#chat_input").attr("value", '');
    }
    
    
    var updateMessages = function(){
    	//alert($("#pos") + ", " + $("#pos").val());
    	var msgPos = $("#pos").val(); 
    	if(msgPos == '' || msgPos == null){
    		$("#pos").attr('value', 0);
    	}
    	var param = "pos=" + $("#pos").val();
    	var accessURL = '/updatemsg?time=' + Math.random();
		$.ajax({
			type: 'GET',
    		data: param,
    		url: accessURL,
    		success: function(data){
    			handleContentReceived(data);
    		}
    	});
		setTimeout(function(){updateMessages();}, 5000);
    }
    updateMessages();
    
    /**
     * Append chat content into content display panel.
     */
    var msgAlert, isInAlert = false;
    var handleContentReceived = function(data){
    	var updateMsg;
    	var jsonData = eval(data);
    	$.each(jsonData, function(idx, item){
//    		alert(idx + ', ' + item.history);
//    		alert('isOnFocus: ' + isOnFocus);
//    		alert((item.history == null) + ", " + typeof(item.history));
    		if(!isOnFocus && !(item.pos == 'null' && item.history == '') && !isInAlert){
    			msgAlert = $.blinkTitle.show();
    			playMusic();
    			isInAlert = true;
    		}
    		
    		var posResult = item.pos
    		if(posResult != 'null'){
    			$("#pos").attr('value', posResult);
    		}
    		updateMsg = item.history;
    	});
    	
    	var chat_content = $("#chat_content"); 
    	chat_content.append(updateMsg);
    	if(chat_content.scrollTop() < 100){
    		chat_content.scrollTop(180);
    	} else {
    		chat_content.scrollTop(chat_content.scrollTop() * 1.5);
    	}
    }
    
   //Disable refresh button.
   document.onkeydown = function(){      
       if(event.keyCode==116){
    	  alert('Refresh page has been forbidden!');
          event.keyCode = 0;      
          event.cancelBubble = true;      
          return false;      
       }      
   	   if(event.keyCode == 13){
   		   sendMessageToServer();  //Enter key
   	   }
    }
   
   /**
    * Init the music content Div
    */
   var initMusicDiv = function(){
	   var musicDiv = $("#musicDiv");
	   if($.browser.safari){ //In Chrome, it shows this.
		   alert('In Chrome!')
		   musicDiv.html('<audio controls="controls" id="music1" loop="true"> <source src="/rsc/msg.mp3" > </audio>');
	   } else {
		   musicDiv.html('<EMBED NAME="music1" SRC="/rsc/msg.mp3" Loop="true" AUTOSTART=false MASTERSOUND>');
	   }
   }
   initMusicDiv();
   
   $("#play").click(function(){
	   playMusic();
   });
   
   /**
    * Play the music
    */
   var playMusic = function(){
	   logger.append('Music has been played. <br/>');
	   //$("#music").html('');
	   //$("#music").html('<embed id="music" autostart="false" src="/rsc/msg.wav" width="1" height="1"></embed>');
	   //document.music1.play();
	   if($.browser.safari){
		   music1.play();
	   } else {
		   $("#music1").play();
	   }
   }
    
    /**
     * Blink the title while received the message.
     */     
	  
    var defaultTitle = 'Welcome to Use 4UrChat';
    $.extend({     
        /**    
         * Call: var timerArr = $.blinkTitle.show();    
         *          $.blinkTitle.clear(timerArr);    
         */    
        blinkTitle : {     
            show : function() { //When new messages received, blink     
                var step=0;     
         
                var timer = setInterval(function() {
                    step++;     
                    if (step==3) {
                    	step=1;
                    };
                    if (step==1) {
                    	logger.append("> Title Default");
                    	document.title = defaultTitle;
                    };     
                    if (step==2) {
                    	logger.append("> Title New");
                    	document.title = '[New Message]' + defaultTitle;
                    };
                }, 500);     
                     
                return timer;     
            },     
                 
            clear : function(timerArr) {    //Clear the blink effect
                if(timerArr) {
                    clearInterval(timerArr);      
                    document.title = defaultTitle;
                    timerArr = null;
                };
            }     
        }     
    });
    
    var isOnFocus = false;
    /**
     * Update on focus status
     */
    $("#chat_input").focus(function(){
        isOnFocus = true;
        if(msgAlert){
        	isInAlert = false;
        	logger.append("Timer Cleared <br/>");
        	$.blinkTitle.clear(msgAlert);
        }
    });
    $("#chat_input").blur(function(){
    	isOnFocus = false;
    });
    
    /**
     * Bind the Enter Key Event
     *
    $(window).keydown(function(event){
    	switch(event.keyCode){
    		case 13: //Enter key
    			sendMessageToServer();
    			break;
//    		case 116: //F5 
//    			alert('Refresh action has been FORBIDDEN!');
//    			break;
    		default:
    			break;
    	}
    }); */
    
    
  });